package com.tongqin.distributed;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author yuantongqin
 * @date 2018/7/9 下午4:22
 *
 *
 * 客户端的建立连接
 */
public class RpcTransport {

    private String host;
    private int port;

    public RpcTransport(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public Object send(RpcRequest request){

        Socket socket = null;
        try {
            socket = new Socket(this.host,this.port);
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(request);
            outputStream.flush();
            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
            Object object = inputStream.readObject();
            inputStream.close();
            outputStream.close();
            return object;


        } catch (Exception e) {
            e.printStackTrace();
            throw  new RuntimeException("==发送失败==",e);
        }finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }



}
